/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sniff;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.PacketReceiver;
import jpcap.packet.*;
/**
 *
 * @author DUYKIENBK
 */
public class Sniff {
    


    /**
     * @param args the command line arguments
     */
    private static LogWindow lw;
    public static void main(String[] args) {
        // TODO code application logic here
        String[] a={"0"};
        try{
            //emailsender e=new emailsender();
           // e.start();
           // test();
            //PricewithTime price = new PricewithTime();
            //price.start();
            lw=new LogWindow();
            lw.setVisible(true);
            test2(a);
            (new Counter()).start();
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    public static void test(){
NetworkInterface[] devices = JpcapCaptor.getDeviceList();

//for each network interface
for (int i = 0; i < devices.length; i++) {
  //print out its name and description
  System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")");

  //print out its datalink name and description
  System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");

  //print out its MAC address
  System.out.print(" MAC address:");
  for (byte b : devices[i].mac_address)
    System.out.print(Integer.toHexString(b&0xff) + ":");
  System.out.println();

  //print out its IP address, subnet mask and broadcast address
  for (NetworkInterfaceAddress a : devices[i].addresses)
    System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);
}

try{

JpcapCaptor captor=JpcapCaptor.openDevice(devices[0], 65535, false, 50000);

//call processPacket() to let Jpcap call PacketPrinter.receivePacket() for every packet capture.
//captor.processPacket(100,new PacketPrinter());

captor.setFilter("(dst host 192.168.1.100) and (dst port 51955)", true);

//captor.
//System.out.println(captor.received_packets);
System.out.println(captor.getPacket().data.toString());

//captor.processPacket(100,new PacketPrinter());
System.out.println(captor.received_packets);
//captor.
captor.close();
}catch(Exception e)
{
    e.printStackTrace();
}



        
    }
    
  public static void test2(String[] args) throws Exception {
      NetworkInterface[] devices = JpcapCaptor.getDeviceList();
		if(args.length<1){
			System.out.println("usage: java Tcpdump <select a number from the following>");
			
			for (int i = 0; i < devices.length; i++) {
				System.out.println(i+" :"+devices[i].name + "(" + devices[i].description+")");
				System.out.println("    data link:"+devices[i].datalink_name + "("
						+ devices[i].datalink_description+")");
				System.out.print("    MAC address:");
				for (byte b : devices[i].mac_address)
					System.out.print(Integer.toHexString(b&0xff) + ":");
				System.out.println();
				for (NetworkInterfaceAddress a : devices[i].addresses)
					System.out.println("    address:"+a.address + " " + a.subnet + " "
							+ a.broadcast);
			}
		}else{
			JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])], 20000, false, 20);
                        jpcap.setFilter("(dst host 192.168.1.100) and (dst port 51955)", true);
			jpcap.loopPacket(-1, new Tcpdump(){
                        @Override
                            public void receivePacket(Packet packet) {

                            String noidung="";
                            byte[] b = packet.data;
                            if(b.length<17)
                                return;
                            if(b[3]==98)
                                return;
                            if(b[3] !=61) // byte thu 4 = 61 la goi tin chat
                                return;
                            String may=tenmay(packet);
                            System.out.println(may);
                            byte [] a = new byte[b.length-16];
                            try{
                                for(int i=0;i<17;i++){
                                // System.out.println(b[i]);

                                }
                                for(int i=0;i<a.length;i++){
                                    a[i] = b[i+16];
                                }

                            noidung = new String (a,"UTF-16LE");

                             System.out.println(noidung);
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                         //   char b=(char)a[0];
                         //   if (b=='') System.out.println("Con lon lai");
                                 //   String value = new String(packet.data);
                            
                            sendinfo(may,noidung);
                            lw.addrow(may, noidung);

                            //log
                            /**
                            Calendar c=Calendar.getInstance();
                            Long unixtime=c.getTimeInMillis();
                           // String line=unixtime+"\t|"+may+"\t|"+noidung;
                            String line=c.get(Calendar.HOUR_OF_DAY)+":"+ c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" "+c.get(Calendar.DAY_OF_MONTH)+"/"+c.get(Calendar.MONTH)+"/"+c.get(Calendar.YEAR)+"\t|"+may+"\t|"+noidung;
                             savetologfile(line)    ;  

                             String noidung1=noidung.trim();
                             if((noidung1.indexOf("tra")!=-1) || (noidung1.indexOf("tre")!=-1)||(noidung1.indexOf("cha")!=-1)||(noidung1.indexOf("cka")!=-1)||(noidung1.indexOf("che")!=-1)||(noidung1.indexOf("cke")!=-1)||(noidung1.indexOf("chanh")!=-1)||(noidung1.indexOf("chank")!=-1)||(noidung1.indexOf("tranh")!=-1)) {
                                 savetotradafile(line);
                             }
                             ***/
                            }

                        public String tenmay (Packet packet){
                    //System.out.println(packet.header.toString());
                    //System.out.println(packet.toString());
                            //String ip=Stringbetween(packet.toString(),"192.168.1.","->/");
                            //return (String.valueOf(Integer.parseInt(ip)-100));
                            return(Stringbetween(packet.toString(),"192.168.1.","->/"));
                    }
                    public  String Stringbetween(String s1, String s2, String s3){
                        try{
                        int b = s1.indexOf(s2);
                        int e = s1.indexOf(s3, b);
                    String s ;
                    int c= Integer.parseInt(s1.substring(b+s2.length(), e));
                    c= c-100;
                    s = String.valueOf(c);
                    return(s);
                        }catch(Exception e){
                            return("");
                        }
                    }

                    public  void sendinfo(String may, String noidung) {
                        // this machine is client
                          try {
                              String data = may + "&&" + noidung;
                             Socket skt = new Socket("192.168.1.90", 1234);
                             PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
                             System.out.print("Sending string: '" + data + "'\n");
                             out.print(data);
                             out.close();
                             skt.close();         

                          }
                          catch(Exception e) {
                             e.printStackTrace();
                          }
                    }

                    private  void savetologfile(String line) {
                      try{
                          // Create file 
                          FileWriter fstream = new FileWriter("log.txt",true);
                          BufferedWriter out = new BufferedWriter(fstream);
                          out.write(line + "\n");
                          //Close the output stream
                          out.close();
                      }catch (Exception e){//Catch exception if any
                       e.printStackTrace();
                      }
                    }

                    private void savetotradafile(String line) {
                       try{
                          // Create file 
                          FileWriter fstream = new FileWriter("trada.txt",true);
                          BufferedWriter out = new BufferedWriter(fstream);
                          out.write(line + "\n");
                          //Close the output stream
                          out.close();
                      }catch (Exception e){//Catch exception if any
                       e.printStackTrace();
                      }   
                    }                        
                        });
		}
  }
    
    
}



class Tcpdump implements PacketReceiver {
    @Override
  public void receivePacket(Packet packet) {
      
  }



}


/******************************
 * Chuc nang kiem tra tk am va kiem tra tra da
 * 
 * 
 */


class emailsender extends Thread {
    @Override
    public void run(){
        while(1==1){
            try {
                Calendar cal = Calendar.getInstance();
                int i=cal.get(Calendar.HOUR)*60+cal.get(Calendar.MINUTE);
                if(360<i && i<390){
                    int j=0;
                    while(!trutk() && j<3) j++; 
                    sendEmail();
                    File f=new File("trada.txt");
                    f.renameTo(new File("trada-"+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+" "+cal.get(Calendar.HOUR_OF_DAY)+"h.txt"));                    
                }
                sleep(1800000);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    private boolean trutk(){   
        //kiem tra tk am
        try{
            FileWriter fstream = new FileWriter("trutaikhoan.txt",false);
            BufferedWriter out = new BufferedWriter(fstream);
            ResultSet entry=selectdb("select (select UserName from usertb where UserId=paymenttb.UserId),paymenttb.`Amount`,paymenttb.VoucherDate,paymenttb.`VoucherTime`,(select UserName from usertb where UserId=paymenttb.`StaffId`) from paymenttb where VoucherDate=CURDATE();");
            if(entry==null) {
                System.out.println("ko query dc du lieu");
                return false;
            }
            while (entry.next()) {
                    out.write(entry.getString(1) + "\t|"+entry.getInt(2)+"\t|"+entry.getDate(3)+ " "+entry.getTime(4)+"\t|"+entry.getString(5));
                } //end while
            // Create file 

            //Close the output stream
            out.close();
            return true;
        }catch (Exception e){//Catch exception if any
            e.printStackTrace();
            return false;
        }    
    }

    private ResultSet selectdb(String query) {
        String dbtime;
        String dbUrl = "jdbc:mysql://localhost/ddm";
        String dbClass = "com.mysql.jdbc.Driver";
    //   String query = "Select * FROM users";

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection (dbUrl,"abc123","Khongbiet$!@#$");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);

        //  while (rs.next()) {
        //       dbtime = rs.getString(1);
        //        System.out.println(dbtime);
        //    } //end while

          
            return rs;
        } //end try

        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public boolean sendEmail() {
            String from = "game18tdn@gmail.com";
            String[] to = {"matran19900@gmail.com","matran19900@yahoo.com","huancao_8x@yahoo.com","y2kcomputer.com@gmail.com","dovanlai@gmail.com"};
            String subject = "Theo doi tra da va tru tai khoan";
            String bodyText = "Xem trong 2 file attach";


            final String username = "game18tdn@gmail.com";
            final String password = "GaMe!*TDN";

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");

            Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                    }
            });

            try {
                InternetAddress[] recv=new InternetAddress[to.length];
                for(int i=0;i<to.length;i++) {
                    recv[i]=new InternetAddress(to[i]);
                }
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.setRecipients(Message.RecipientType.TO, recv);
                message.setSubject(subject);
                message.setSentDate(new Date());

                //
                // Set the email message text.
                //
                MimeBodyPart messagePart = new MimeBodyPart();
                messagePart.setText(bodyText);

                //
                // Set the email attachment file 1
                //
                MimeBodyPart attachmentPart1 = new MimeBodyPart();
                FileDataSource fileDataSource1 = new FileDataSource("trutaikhoan.txt") {
                    @Override
                    public String getContentType() {
                        return "application/octet-stream";
                    }
                };
                attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
                attachmentPart1.setFileName(fileDataSource1.getName());
                
                //
                // Set the email attachment file 2
                //
                MimeBodyPart attachmentPart2 = new MimeBodyPart();
                FileDataSource fileDataSource2 = new FileDataSource("trada.txt") {
                    @Override
                    public String getContentType() {
                        return "application/octet-stream";
                    }
                };
                attachmentPart2.setDataHandler(new DataHandler(fileDataSource2));
                attachmentPart2.setFileName(fileDataSource2.getName());

                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messagePart);
                multipart.addBodyPart(attachmentPart1);
                multipart.addBodyPart(attachmentPart2);

                message.setContent(multipart);

                Transport.send(message);
                return true;
            } catch (MessagingException e) {
                e.printStackTrace();
                System.out.println("Send fail!");
                return false;
            }
        }   
}